<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>俄罗斯方块</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <style>
        * {
            box-sizing: border-box;
            touch-action: none;
            margin: 0;
            padding: 0;
        }
        html, body {
            height: 100%;
            overflow: hidden;
        }
        body {
            background: #f0f0f0;
            font-family: Arial, sans-serif;
            position: relative;
        }

        /* 得分样式 */
        #score {
            position: absolute;
            left: 8px;
            top: 8px;
            font-size: 16px;
            padding: 4px 8px;
            border-radius: 4px;
            color: #fff;
            z-index: 2;
            background: rgba(0,0,0,0.72);
        }

        /* 游戏容器 */
        #game-wrapper {
            width: 100%;
            height: calc(100% - 100px);
            max-width: 400px;
            margin: 0 auto;
            padding: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        canvas {
            width: 100%;
            height: 100%;
            border: 2px solid #333;
            background: #fff;
        }

        /* 控制按钮 */
        #controls {
            position: fixed;
            bottom: 20px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 15px;
            padding: 0 10px;
            z-index: 100;
        }
        .control-btn {
            width: 55px;
            height: 55px;
            border-radius: 50%;
            background: #4CAF50;
            color: white;
            border: none;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            transition: all 0.1s;
            -webkit-tap-highlight-color: transparent;
            touch-action: manipulation;
        }
        .control-btn:active {
            transform: scale(0.95);
            background: #45a049;
        }
        #rotate-btn {
            background: #2196F3;
        }

        /* 游戏结束弹窗 */
        #game-over {
            display: none;
            position: fixed;
            top: 45%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 25px 35px;
            border-radius: 12px;
            box-shadow: 0 0 25px rgba(0,0,0,0.15);
            text-align: center;
            z-index: 101;
            width: 80%;
            max-width: 280px;
        }
        #game-over h2 {
            margin: 0 0 12px 0;
            color: #333;
            font-size: 22px;
            white-space: nowrap;
        }
        #final-score {
            font-size: 24px;
            color: #f44336;
            font-weight: bold;
            white-space: nowrap;
        }
        #restart-btn {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 15px;
            transition: all 0.3s;
        }
        #restart-btn:active {
            background: #45a049;
        }
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 99;
            display: none;
        }
    </style>
</head>
<body>
    <div id="score">得分: 0</div>
    <div id="game-wrapper">
        <canvas id="game"></canvas>
    </div>
    
    <div id="controls">
        <button class="control-btn" id="left-btn">←</button>
        <button class="control-btn" id="down-btn">↓</button>
        <button class="control-btn" id="right-btn">→</button>
        <button class="control-btn" id="rotate-btn">↻</button>
    </div>

    <div id="game-over">
        <h2>游戏结束！</h2>
        <p>最终得分: <span id="final-score">0</span></p>
        <button id="restart-btn">重新开始</button>
    </div>
    <div id="overlay" class="overlay"></div>

<script>
// 游戏配置
const SHAPES = [
    [[1,1,1,1]], [[1,1,1],[0,1,0]], [[1,1,1],[1,0,0]], 
    [[1,1,1],[0,0,1]], [[1,1],[1,1]], [[1,1,0],[0,1,1]], 
    [[0,1,1],[1,1,0]]
];
const COLORS = ['#00f0f0','#f0a000','#f0f000','#a000f0','#f00000','#00f000','#0000f0'];
const COLS = 10, ROWS = 20;

// 游戏状态
let canvas, ctx, BLOCK_SIZE;
let board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
let currentPiece = null, score = 0, gameInterval, gameOver = false;

// DOM元素
const dom = {
    score: document.getElementById('score'),
    gameOver: document.getElementById('game-over'),
    finalScore: document.getElementById('final-score'),
    restartBtn: document.getElementById('restart-btn'),
    overlay: document.getElementById('overlay')
};

// 初始化画布
function initCanvas() {
    canvas = document.getElementById('game');
    ctx = canvas.getContext('2d');
    const controlsHeight = document.getElementById('controls').offsetHeight;
    const scoreHeight = document.getElementById('score').offsetHeight;
    const maxHeight = window.innerHeight - controlsHeight - scoreHeight - 40;
    const maxWidth = document.getElementById('game-wrapper').offsetWidth - 20; // 减去padding
    
    // 确保在小屏幕上保持合适的宽高比
    const aspectRatio = ROWS / COLS;
    let canvasWidth = maxWidth;
    let canvasHeight = canvasWidth * aspectRatio;
    
    if (canvasHeight > maxHeight) {
        canvasHeight = maxHeight;
        canvasWidth = canvasHeight / aspectRatio;
    }
    
    BLOCK_SIZE = canvasWidth / COLS;
    
    canvas.width = COLS * BLOCK_SIZE;
    canvas.height = ROWS * BLOCK_SIZE;
    
    // 设置canvas的CSS尺寸，确保显示正确
    canvas.style.width = `${canvasWidth}px`;
    canvas.style.height = `${canvasHeight}px`;
}

// 方块生成
function createPiece() {
    const type = Math.floor(Math.random() * SHAPES.length);
    return {
        shape: SHAPES[type],
        color: COLORS[type],
        x: Math.floor(COLS/2) - Math.floor(SHAPES[type][0].length/2),
        y: 0
    };
}

// 绘制模块
function drawBlock(x, y, color) {
    ctx.fillStyle = color;
    ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1);
    ctx.strokeStyle = '#ddd';
    ctx.strokeRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
}

// 主绘制
function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制棋盘
    board.forEach((row, y) => row.forEach((color, x) => {
        if (color) drawBlock(x, y, color);
    }));
    
    // 绘制当前方块
    currentPiece?.shape.forEach((row, dy) => row.forEach((value, dx) => {
        value && drawBlock(currentPiece.x + dx, currentPiece.y + dy, currentPiece.color);
    }));
}

// 碰撞检测
function collision() {
    return currentPiece.shape.some((row, dy) => row.some((value, dx) => 
        value && (
            currentPiece.x + dx < 0 ||
            currentPiece.x + dx >= COLS ||
            currentPiece.y + dy >= ROWS ||
            board[currentPiece.y + dy]?.[currentPiece.x + dx]
        )
    ));
}

// 合并方块
function merge() {
    currentPiece.shape.forEach((row, dy) => row.forEach((value, dx) => {
        value && (board[currentPiece.y + dy][currentPiece.x + dx] = currentPiece.color);
    }));
}

// 旋转
function rotate() {
    const newShape = currentPiece.shape[0].map((_, i) => 
        currentPiece.shape.map(row => row[i]).reverse()
    );
    const oldShape = currentPiece.shape;
    currentPiece.shape = newShape;
    if (collision()) currentPiece.shape = oldShape;
}

// 消除行
function clearLines() {
    let lines = 0;
    for (let y = ROWS-1; y >= 0; y--) {
        if (board[y].every(c => c)) {
            board.splice(y, 1);
            board.unshift(Array(COLS).fill(0));
            lines++; y++;
        }
    }
    if (lines) {
        score += lines * 100;
        dom.score.textContent = `得分: ${score}`;
    }
}

// 下落逻辑
function moveDown() {
    if (!currentPiece || gameOver) return;
    currentPiece.y++;
    if (collision()) {
        currentPiece.y--;
        merge();
        clearLines();
        currentPiece = null;
    }
    draw();
}

// 游戏更新
function update() {
    if (gameOver) return;
    
    if (!currentPiece) {
        currentPiece = createPiece();
        if (collision()) return showGameOver();
    }
    
    currentPiece.y++;
    if (collision()) {
        currentPiece.y--;
        merge();
        clearLines();
        currentPiece = null;
    }
    draw();
}

// 游戏控制
function resetGame() {
    board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
    score = 0, gameOver = false, currentPiece = null;
    dom.score.textContent = '得分: 0';
    dom.gameOver.style.display = dom.overlay.style.display = 'none';
    clearInterval(gameInterval);
    gameInterval = setInterval(update, 200); // 加快游戏速度
    draw();
}

function showGameOver() {
    gameOver = true;
    dom.finalScore.textContent = score;
    dom.gameOver.style.display = dom.overlay.style.display = 'block';
    clearInterval(gameInterval);
}

// 事件监听
function setupControls() {
    const controls = {
        left:  () => { if (currentPiece) { currentPiece.x--; collision() && currentPiece.x++; } },
        right: () => { if (currentPiece) { currentPiece.x++; collision() && currentPiece.x--; } },
        down:  moveDown,
        rotate: () => currentPiece && rotate()
    };

    // 按钮事件
    document.getElementById('left-btn').addEventListener('mousedown', controls.left);
    document.getElementById('right-btn').addEventListener('mousedown', controls.right);
    document.getElementById('down-btn').addEventListener('mousedown', controls.down);
    document.getElementById('rotate-btn').addEventListener('mousedown', controls.rotate);

    // 触摸事件 - 增强响应性
    ['touchstart', 'touchend'].forEach(evt => {
        document.getElementById('left-btn').addEventListener(evt, e => { 
            e.preventDefault(); 
            if(evt === 'touchstart') controls.left(); 
        }, {passive: false});
        document.getElementById('right-btn').addEventListener(evt, e => { 
            e.preventDefault(); 
            if(evt === 'touchstart') controls.right(); 
        }, {passive: false});
        document.getElementById('down-btn').addEventListener(evt, e => { 
            e.preventDefault(); 
            if(evt === 'touchstart') controls.down(); 
        }, {passive: false});
        document.getElementById('rotate-btn').addEventListener(evt, e => { 
            e.preventDefault(); 
            if(evt === 'touchstart') controls.rotate(); 
        }, {passive: false});
    });
    
    // 添加连续按下功能
    let pressIntervals = {};
    const startContinuousMove = (direction, delay) => {
        if(pressIntervals[direction]) return;
        pressIntervals[direction] = setInterval(() => {
            controls[direction]();
            draw();
        }, delay);
    };
    
    const stopContinuousMove = (direction) => {
        if(pressIntervals[direction]) {
            clearInterval(pressIntervals[direction]);
            pressIntervals[direction] = null;
        }
    };
    
    // 长按支持
    document.getElementById('left-btn').addEventListener('touchstart', () => startContinuousMove('left', 100), {passive: false});
    document.getElementById('right-btn').addEventListener('touchstart', () => startContinuousMove('right', 100), {passive: false});
    document.getElementById('down-btn').addEventListener('touchstart', () => startContinuousMove('down', 50), {passive: false});
    
    document.getElementById('left-btn').addEventListener('touchend', () => stopContinuousMove('left'), {passive: false});
    document.getElementById('right-btn').addEventListener('touchend', () => stopContinuousMove('right'), {passive: false});
    document.getElementById('down-btn').addEventListener('touchend', () => stopContinuousMove('down'), {passive: false});
    document.getElementById('left-btn').addEventListener('touchcancel', () => stopContinuousMove('left'), {passive: false});
    document.getElementById('right-btn').addEventListener('touchcancel', () => stopContinuousMove('right'), {passive: false});
    document.getElementById('down-btn').addEventListener('touchcancel', () => stopContinuousMove('down'), {passive: false});

    // 键盘事件
    document.addEventListener('keydown', e => {
        if (gameOver) return;
        switch(e.keyCode) {
            case 37: controls.left(); break;
            case 39: controls.right(); break;
            case 40: controls.down(); break;
            case 38: controls.rotate(); break;
            case 82: resetGame(); break;
        }
        draw();
    });

    dom.restartBtn.addEventListener('click', resetGame);
}

// 初始化
function init() {
    initCanvas();
    setupControls();
    resetGame();
    window.addEventListener('resize', () => {
        initCanvas();
        draw();
    });
}

// 启动游戏
init();
</script>
</body>
</html>